﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
namespace Lion.WeiXin.Controllers
{
   [PermissionFilter]
    public class DictionaryController : Controller
    {
        //
        // GET: /Dictionary/

       DBContext db = new DBContext();

        public ActionResult Index()
        {
            InitProductType("000");

            return View();
        }

        private void InitProductType(string selectID)
        {
            //加载产品类型
            List<DictionaryModel> dic_pro_types = db.Dictionarys.GetList("len(Dic_Key)=3 and IsDelete=0");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "000", Text = "请选择" });

            foreach (DictionaryModel item in dic_pro_types)
            {
                if (item.Dic_Key == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.Dic_Key.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData["selParentKey"] = selectTypes;
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string dicKey,string parentKey, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示  ,           //只显示未删除的
            string where = " IsDelete=0 ";
            dicKey = HttpUtility.UrlDecode(dicKey);
            if (!string.IsNullOrWhiteSpace(dicKey))
            {
                where += string.Format(" and Dic_Key={0}", dicKey);
               }
            if (parentKey != "000")
            {
                where += string.Format(" and Dic_Key like '{0}%'", parentKey);
            }
            List<DictionaryModel> list = new List<DictionaryModel>();
            int totalCount = 0;
            list = db.Dictionarys.GetList(pageSize, currentPage, where);
            //排序
            list=list.OrderBy(n => n.Dic_Key).ToList();
            totalCount = db.Dictionarys.GetRecordCount(where);

 

            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }
       /// <summary>
       /// 获取所有父key 的孩子字典值
       /// </summary>
       /// <param name="parentKey"></param>
       /// <returns></returns>
        public JsonResult GetItems(string parentKey)
        {
            List<DictionaryModel> list = new List<DictionaryModel>();
            list = db.Dictionarys.GetList(string.Format(" IsDelete=0 and Dic_Key like '{0}%' and len(Dic_Key)={1}",parentKey,parentKey.Length+3));
            return Json(new { data = list });
        }

        public ActionResult Show()
        {
            string ID = Request.QueryString["ID"];
            if (string.IsNullOrEmpty(ID))
            {
                return Redirect(Request.RawUrl);
            }
            DictionaryModel model = db.Dictionarys.GetModel(int.Parse(ID));
            ViewBag.Dic_ParentKey = model.Dic_Key.Substring(0, model.Dic_Key.Length - 3);
            return View(model);
        }

        public ActionResult Create()
        {
            string pkey = Request.QueryString["ParentKey"];
            ViewBag.ParentKey = pkey;
            List<DictionaryModel> list = db.Dictionarys.GetList(string.Empty);   
            //自动产生一个Key 键值
            if (pkey == "000")
            {
                //自动产生一个一级子节点(3位一段)
                List<DictionaryModel> topDics= list.Where(n => n.Dic_Key.Length == 3).ToList();
                if (topDics.Count == 0)
                {
                    //数据库中无一条记录,所有子节点从100开始
                    ViewBag.DicKey = "100";
                }
                else
                {
                    long maxKey = topDics.Max(n => long.Parse(n.Dic_Key));
                    ViewBag.DicKey = (maxKey + 1).ToString();
                }
            }
            else
            { 
                //查找当前节点的所有子节点，并且
                List<DictionaryModel> childDics = list.Where(n => n.Dic_Key.IndexOf(pkey)==0&&n.Dic_Key!=pkey).ToList();
                if (childDics.Count == 0)
                {
                    //无子节点 
                    ViewBag.DicKey = pkey + "001";
                }
                else
                {
                    long maxKey = childDics.Max(n => long.Parse(n.Dic_Key));
                    ViewBag.DicKey = (maxKey + 1).ToString();
                }
            }
            return View();
        }


        public ActionResult Save(FormCollection form)
        {
            string action = Request.QueryString["action"];
            DictionaryModel model = new DictionaryModel();
            UpdateModel(model);
            

            string result = SaveStateEnum.OK.ToString();
            try
            {
                if (action == ActionEnum.Create.ToString())
                {
                    model.Creator = CurrentUser.UserName;
                    model.CreateDate = DateTime.Now;
                    model.LastUpdateDate = DateTime.Now;
                    model.IsDelete = 0;
                    model.Last_Changed_By = CurrentUser.UserName;
                    db.Dictionarys.Add(model);
                }
                else if (action == ActionEnum.Update.ToString())
                {
                    model.LastUpdateDate = DateTime.Now;
                    db.Dictionarys.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    db.Dictionarys.DeleteLogic(IDs);
                    result = SaveStateEnum.OK.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

    }
}
